package com.globallogic.qdumper.jdbc;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class OdbcQueryHelper
{

    private Connection connection;

    public void connect(String dsn, String user, String password) throws Exception
    {
        if ( dsn == null || dsn.equals("") )
        {
            throw new IllegalArgumentException("DSN Name must be specified");
        }

        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();

        String url = "jdbc:odbc:" + dsn;

        connection = DriverManager.getConnection(url, user, password);
    }

    public ResultSet executeQuery(String query) throws SQLException
    {
        if ( query == null )
        {
            throw new IllegalArgumentException("Query is not to be null");
        }
        if ( connection == null || connection.isClosed() )
        {
            throw new IllegalStateException("Conection closed.");
        }

        Statement statement = connection.createStatement();

        ResultSet result = statement.executeQuery(query);

        return result;
    }

    public void printMetaData() throws SQLException
    {
        DatabaseMetaData meta = connection.getMetaData();
        ResultSet res = meta.getTables(null, null, null, new String[]
            {
            "TABLE"
            });
        System.out.println("List of tables: ");
        while ( res.next() )
        {
            System.out.println("   " + res.getString("TABLE_CAT") + ", "
                + res.getString("TABLE_SCHEM") + ", " + res.getString("TABLE_NAME") + ", "
                + res.getString("TABLE_TYPE") + ", " + res.getString("REMARKS"));
        }
        res.close();
    }

    public void disconnect()
    {
        if ( connection != null )
        {
            try
            {
                connection.close();
            }
            catch ( SQLException e )
            {
                e.printStackTrace();
            }
        }
    }
}
